package com.tarena.lbs.basic.web.service;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.basic.web.repository.AdminRepository;
import com.tarena.lbs.common.passport.encoder.JwtEncoder;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.passport.param.AdminLoginParam;
import com.tarena.lbs.pojo.passport.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginService {

    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private JwtEncoder jwtEncoder;
    public LoginVO doLogin(AdminLoginParam param) throws BusinessException {
        //查询对应的adminPO是否存在
        AdminPO adminPO = getAndCheckAdmin(param.getPhone());
        //对比密码是否正确
        matchPassword(param.getPassword(),adminPO.getAccountPassword());
        //生成jwt
        String jwt = generateJWT(adminPO);
        //封装VO返回
        return new LoginVO(jwt,adminPO.getId(),adminPO.getNickname());
    }

    private String generateJWT(AdminPO adminPO) throws BusinessException {
        UserPrinciple userPrinciple = new UserPrinciple();
        userPrinciple.setId(adminPO.getId());
        userPrinciple.setNickname(adminPO.getNickname());
        userPrinciple.setRole(adminPO.getAccountType()==0 ? Roles.ADMIN : Roles.SHOP);
        return jwtEncoder.generateToken(userPrinciple);
    }

    private void matchPassword(String password, String accountPassword) throws BusinessException {
        boolean equals = StringUtils.equals(password, accountPassword);
        Asserts.isTrue(!equals,new BusinessException("-2","密码不正确！"));
    }

    private AdminPO getAndCheckAdmin(String phone) throws BusinessException {
        QueryWrapper<AdminPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_phone",phone);
        AdminPO adminPO = adminRepository.getOne(queryWrapper);
        Asserts.isTrue(adminPO==null,new BusinessException("-2","用户名不存在！"));
        return adminPO;
    }
}
